package com.ruoyi.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.core.domain.entity.SysRole;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.system.domain.MonitorRole;
import com.ruoyi.system.mapper.MonitorRoleMapper;
import com.ruoyi.system.service.MonitorRoleService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class MonitorRoleServiceImpl extends ServiceImpl<MonitorRoleMapper, MonitorRole> implements MonitorRoleService {

    @Override
    public List<Long> selectList(Long roleId) {
        LambdaQueryWrapper<MonitorRole> query = new LambdaQueryWrapper<MonitorRole>()
                .eq(MonitorRole::getRoleId, roleId);
        List<MonitorRole> list = baseMapper.selectList(query);
        return list.stream().map(MonitorRole::getMonitorConfigId).collect(Collectors.toList());
    }

    @Transactional
    @Override
    public void update(Long roleId, List<Long> configIds) {
        LambdaQueryWrapper<MonitorRole> deleteQuery = new LambdaQueryWrapper<MonitorRole>()
                .eq(MonitorRole::getRoleId, roleId);
        baseMapper.delete(deleteQuery);

        if (CollectionUtils.isEmpty(configIds)) {
            return;
        }
        List<MonitorRole> addList = configIds.stream().map(configId -> {
            MonitorRole add = new MonitorRole();
            add.setRoleId(roleId);
            add.setMonitorConfigId(configId);
            return add;
        }).collect(Collectors.toList());

        this.saveBatch(addList);
    }

    @Override
    public List<Long> selectCurrentList() {
        List<Long> roles = SecurityUtils.getLoginUser().getUser().getRoles().stream().map(SysRole::getRoleId).collect(Collectors.toList());
        LambdaQueryWrapper<MonitorRole> query = new LambdaQueryWrapper<MonitorRole>()
                .in(MonitorRole::getRoleId, roles);
        List<MonitorRole> list = baseMapper.selectList(query);
        return list.stream().map(MonitorRole::getMonitorConfigId).distinct().collect(Collectors.toList());
    }
}
